<script setup lang="ts">
import { getCommonCourseTags, getCommonStudyTreeTags } from '@/api/study/studySquare';
import { useCourseStore } from '@/stores/useCourseStore'; // Pinia store for courses
import { useStudyTreeStore } from '@/stores/useStudyTreeStore'; // Pinia store for study trees
import { message } from 'ant-design-vue';
import { onMounted, ref, watch } from 'vue';
import type { StudyTreeItem } from '@/types/course/studyTree';
import { fetchStudyTreeOssUrlApi, fetchStudyTreeSearch } from '@/api/study/studyTree';
import { getCourseMetaApi } from '@/api/study/course';

interface Tag {
  tagId: string;
  tagName: string;
}

const props = defineProps<{
  cardType: string;
}>();

const emit = defineEmits<{
  (e: 'changeCardType', type: string): void;
}>()

const courseStore = useCourseStore();
const studyTreeStore = useStudyTreeStore();

const categories = ref<Tag[]>([]);
const selectedCategory = ref<string>('全部');
const viewType = ref<string>(props.cardType);

const keyword = ref<string>('');
const tag = ref<string>('');
const page = ref<number>(1);

// 获取标签分类
const fetchCategories = async () => {
  try {
    let response;
    // 应该根据上面的路由判断，而不是直接判断 viewType
    if (viewType.value === '技能树') {
      response = await getCommonStudyTreeTags();
      categories.value = [{ tagId: '', tagName: '全部' }, ...response];
    }
    else if (viewType.value === '课程') {
      response = await getCommonCourseTags();
      categories.value = [
        { tagId: '', tagName: '全部' },
        ...response.map((tagName: string, index: number) => ({
          tagId: index.toString(),
          tagName,
        })),
      ];
    }
  }
  catch (error) {
    console.error('Failed to fetch categories:', error);
    message.error('请求标签时出现错误');
  }
};

// 获取技能树数据，并处理 imageUrl
const fetchStudyTreeMetadata = async () => {
  const params = {
    tags: tag.value || '',
    page: page.value.toString(),
    size: '100',
    keyword: keyword.value || '',
  };

  try {
    const response = await fetchStudyTreeSearch(params)

    const studyTreeData: StudyTreeItem[] = await Promise.all(
      response.data.map(async (item: StudyTreeItem) => {
        if (item.imageUrl && !item.imageUrl.startsWith('http')) {
          try {
            const urlResponse = await fetchStudyTreeOssUrlApi({ filename: item.imageUrl })
            if (urlResponse.data)
              item.imageUrl = urlResponse.data;
          }
          catch (urlError) {
            console.error('Failed to fetch image URL:', urlError);
            item.imageUrl = ''; // 或者设置为默认图片
          }
        }
        return item;
      }),
    );
    studyTreeStore.setStudyTreeItems(studyTreeData, response.data.total);
  }
  catch (error) {
    console.error('Request failed:', error);
    message.error('获取技能树数据时出现错误');
  }
};

// 获取课程数据
const fetchCourseMetadata = async () => {
  const requestBody = {
    keywords: keyword.value || '',
    tag: tag.value || '',
    page: page.value.toString(),
  };

  try {
    const response = await getCourseMetaApi(requestBody);

    if (response.data) {
      courseStore.setCourses(response.data.records, response.data.total, page.value);
    }
    else {
      console.error('Error in response:', response);
      message.error('获取课程数据失败');
    }
  }
  catch (error) {
    console.error('Request failed:', error);
    message.error('获取课程数据时出现错误');
  }
};

// 搜索处理
const handleSearch = (value: string) => {
  keyword.value = value;
  page.value = 1;
  if (viewType.value === '技能树')
    fetchStudyTreeMetadata();
  else if (viewType.value === '课程')
    fetchCourseMetadata();
};

// 分类点击处理
const handleCategoryClick = (category: string) => {
  selectedCategory.value = category;
  page.value = 1;
};

// 视图切换处理
const handleViewChange = async (key: string) => {
  // 如果当前视图和点击的视图相同，则不进行操作
  if (viewType.value === key)
    return;

  viewType.value = key;
  // 更改外部cardType
  emit('changeCardType', key);
  selectedCategory.value = '全部';
  page.value = 1;
};

// 按钮样式
const getButtonStyle = (isActive: boolean) => ({
  borderColor: 'white',
  fontSize: '1rem',
  marginRight: '10px',
  backgroundColor: isActive ? '#3875f6' : 'white',
  color: isActive ? 'white' : 'black',
});

// 监听 selectedCategory 的变化，更新 tag
watch(selectedCategory, (newVal) => {
  tag.value = newVal === '全部' ? '' : newVal;
  page.value = 1;
});

// 当 keyword、tag、page、viewType 变化时，获取数据
watch([keyword, tag, page, viewType], () => {
  if (viewType.value === '技能树')
    fetchStudyTreeMetadata();
  else if (viewType.value === '课程')
    fetchCourseMetadata();
});

// 当 viewType 变化时，重新获取分类标签
watch(viewType, () => {
  fetchCategories();
  if (viewType.value === '技能树')
    fetchStudyTreeMetadata();

  else if (viewType.value === '课程')
    fetchCourseMetadata();
});

onMounted(async () => {
  await fetchCategories();
  if (viewType.value === '技能树')
    await fetchStudyTreeMetadata();

  else if (viewType.value === '课程')
    await fetchCourseMetadata();
});
</script>

<template>
  <div class="data-market">
    <!-- 顶部菜单：标题和搜索框 -->
    <!-- 视图切换按钮：技能树和课程 -->
    <a-flex style="margin-top: 16px;">
      <a-button
        :style="getButtonStyle(viewType === '技能树')"
        @click="handleViewChange('技能树')"
      >
        技能树
      </a-button>

      <a-button
        :style="getButtonStyle(viewType === '课程')"
        @click="handleViewChange('课程')"
      >
        课程
      </a-button>
      <a-input-search
        v-model:value="keyword"
        placeholder="请输入搜索内容"
        enter-button
        @search="handleSearch"
      />
    </a-flex>

    <a-divider />

    <!-- 分类标签按钮 -->
    <div class="category-menu">
      <a-button
        v-for="category in categories"
        :key="category.tagId"
        :style="getButtonStyle(selectedCategory === category.tagName)"
        @click="handleCategoryClick(category.tagName)"
      >
        {{ category.tagName }}
      </a-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.data-market {
  display: flex;
  flex-direction: column;
  margin-left: 40px;
  margin-right: 20px;
  margin-bottom: 0px;

  .top-menu {
     display: flex;
     h1{
       margin-top: 16px;
       flex: auto;
     }
     .search-bar {
         display: flex;
         align-items: center;
         margin-top: 14px;
         padding: 8px 0px;
         .ant-btn, .ant-select, .ant-input-search {
          margin-right: 16px;
        }
        .ant-btn:last-child, .ant-input-search:last-child {
          margin-right: 0;
        }
      }
  }
  .category-menu {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    gap:10px; // 按钮之间的间距，可选
    margin-bottom: auto;

    .yingyong-tagbutton{
      margin-right: 20px;
      font-size: 1rem;
      padding: 8px 16px;
      border-radius: 0px;

      &:hover {
        background-color: #f0f0f0;
      }

      &.ant-btn-primary {
        background-color: #3875f6;
        color: #fff;
        border: none;

        &:hover {
          background-color: #3875f6;
          color: #fff;
        }
      }
    }
  }

  .search-bar {
    display: flex;
    align-items: center;
    margin-top: 10px;
    font-size: 16px;
  }
  .start-chat-button {
    background-color: #3867ea;
    color: #fff;
    border: none;
    font-size: 16px;
    padding: 7px 20px !important;
    border-radius: 8px;

    &:hover {
      background-color: #3857ea;
      color: #fff;
    }
  }
}
</style>
